
import { FIGHT_END } from '../../config/play_def'
import gacha from '../tool/gacha'
import { Sdk_Platform, WX_AD_CONFIG, OPPO_AD_CONFIG } from '../../frame/constants';
import { UI_Listen, UI_Layer } from '../../config/ui_def'
import util from '../tool/util';
cc.Class({
    extends: cc.Component,

    properties: {
        // light: cc.Node,
        content: cc.Node,
        key_lab: cc.Label,
        ad_btn: cc.Node,
        bigPrice: cc.Sprite,
        bigPrice_lab: cc.Label,
        bigPrice_title: cc.Label,
        closeNode: cc.Node,
        adBanner: cc.Node,
        close_Btn: cc.Node,
        bottomNode: cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:
    initPage() {
        if (!he.pool.getPool('gaChaItem')) {
            he.pool.createPoolSync('gaChaItem', 5, cc.Prefab, 'uimod/gaChaItem')
        }

    },

    updatePage(param) {
        switch (common.sdk_env) {
            case Sdk_Platform.VIVO:
                this.close_Btn.setPosition(0, -600)
                break
            default:
                this.close_Btn.setPosition(0, -600)
                break
        }


        // let gachaRes = he.local.getJson("gachaRes")
        // if (!gachaRes) {
        //     this.gaChaRes = gacha.getGachaid(5001)
        //     // console.log("boxPage Use gacha")
        //     gachaRes = {
        //         res: this.gaChaRes,
        //         getRes: [-1, -1, -1, -1, -1, -1, -1, -1, -1],
        //         openNum: 9
        //     }
        //     this.getRes = gachaRes.getRes
        //     // he.local.setJson('gachaRes', gachaRes)
        // } else {
        //     // console.log("else this.gaChaRes = gachaRes.res ")
        //     this.gaChaRes = gachaRes.res
        //     this.getRes = gachaRes.getRes
        // }I
        if (param.boxId) {
            this.gaChaRes = gacha.getGachaid(param.boxId)//parseInt()
        } else {
            this.gaChaRes = gacha.getGachaid(5001)
        }
        // console.log("boxPage Use gacha")
        let gachaRes = {
            res: this.gaChaRes,
            getRes: [-1, -1, -1, -1, -1, -1, -1, -1, -1],
            openNum: 9
        }
        this.getRes = gachaRes.getRes
        this.closeNode.active = false

        //本次点击打开宝箱的次数
        this.treasureNum = gachaRes.openNum
        this.isOpenNum = 9 - this.treasureNum
        this.keyNum = 3
        this.adNum = 0
        this.treasureGrp = []
        this.isHaveClick = []
        this.isAni = false
        this.gachaListInit()
        this.creatItem()
        this.isShowBanner = false
        // for (let index = 0; index < this.gaChaRes.list.length; index++) {
        //     const element = array[index];
        // }

        this.gaChaList = this.gaChaRes.list
        this.mplist = this.gaChaRes.mplist
        this.spItem = this.gaChaRes.top.split('_')
        this.BigPriceInit()
        gg.eventManager.on('openTreasure', this.getTreasure, this)
        this.adSwitch(true)
    },

    BigPriceInit() {
        if (this.spItem) {
            let item = he.db.getDataByArgs('Item', { id: parseInt(this.spItem[0]) })
            he.log(parseInt(this.spItem[0]), item)
            // this.bigPrice.spriteFrame = he.load.get('item', cc.SpriteAtlas).getSpriteFrame(item.icon)
            this.bigPrice_title.string = `${item.name}`
            this.bigPrice_lab.string = `${item.description}`
            if (item.type == 1 || item.type == 2 || item.type == 4 || item.type == 9) {
                this.bigPrice.spriteFrame = he.load.get('item', cc.SpriteAtlas).getSpriteFrame(item.icon)
                // this.bigPrice_lab.string = `${item.mark}`
            } else {
                this.bigPrice.spriteFrame = he.load.get('skill', cc.SpriteAtlas).getSpriteFrame(item.icon)
                // this.bigPrice_lab.string = `${item.name}`
            }
        }
    },

    closeUI() {
        // this.stopLightSchedule()
        this.adSwitch(false)
        this.node.targetOff(this)
        // let gachaRes = {
        //     res: this.gaChaRes,
        //     getRes: this.getRes,
        //     openNum: this.treasureNum
        // }
        if (this.sc1) {
            this.unschedule(this.bannerInit)
            this.sc1 = null
        }
        if (this.sc2) {
            this.unschedule(this.hideBanner)
            this.sc2 = null
        }
        gg.eventManager.emit('topBar', UI_Listen.TOP_UPDATE_DIAMOND)
        // he.local.setJson('gachaRes', gachaRes)
        for (let i = (this.content.children.length); i > 0; i--) {
            let spt = this.content.children[i - 1].getComponent('gachaItem')
            if (spt) spt.clearInfo()
            he.pool.putElement('gaChaItem', this.content.children[i - 1])
        }
        //不再彈出
        // switch (common.sdk_env) {
        //     case Sdk_Platform.OPPO:
        //         let guideList = he.local.getJson('guideList', 'user')
        //         if(!guideList[6]){
        //             return
        //         }
        //         gg.uiManager.addPage(UI_Layer.Cover, {
        //         name: 'signPage',
        //         cover: true
        //         })
        //         break
        // }
    },

    adSwitch(status) {
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.VIVO:
                    // this.bottomNode.name = VIVO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    break
                case Sdk_Platform.OPPO:
                    let guideList = he.local.getJson('guideList', 'user')
                    if (!guideList[6]) {
                        return
                    }
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFakeOPPO',
                        isShowAd: true,
                        isShowBanner: false,
                        adIndex: 7,
                        position: cc.Vec2(0, -690)
                    })
                    // this.bottomNode.name = OPPO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    break
                case Sdk_Platform.HUAWEI:
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'hwAdPage',
                        cover: false,
                        isShowAd: true,
                        adType: Ad_Type.INSERT,
                        position: 0
                    })
                    break
            }
        } else {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    break
                case Sdk_Platform.VIVO:
                    // this.bottomNode.name = VIVO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    break
                case Sdk_Platform.OPPO:
                    gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFakeOPPO')
                    // this.bottomNode.name = OPPO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    break
                case Sdk_Platform.HUAWEI:
                    if (gg.uiManager.getPage(UI_Layer.Msg, 'hwAdPage')) {
                        gg.uiManager.closePage(UI_Layer.Msg, 'hwAdPage')
                    }
                    break
            }
        }
    },

    closeServer() {
        if (!this.isAni) {
            if (this.treasureNum != 0) {
                switch (common.sdk_env) {
                    case Sdk_Platform.WECHAT:
                        let ver_info = he.local.getJson('ver_info')
                        if (ver_info.banner_mistake) {
                            if (!this.isShowBanner) {
                                this.isShowBanner = true
                                this.sc1 = this.scheduleOnce(this.bannerInit, 0.5)
                                this.sc2 = this.scheduleOnce(this.hideBanner, 2)
                            } else {
                                this.closeNode.active = true
                            }
                        } else {
                            this.closeNode.active = true
                        }
                        break
                    default:
                        this.closeNode.active = true
                        break
                }
            } else {
                gg.eventManager.emit('timeCheck')
                this.uiBase.closePage()
            }
        }
    },

    bannerInit() {
        this.adBanner.name = WX_AD_CONFIG.bannerId[0]
        /// 显示
        he.ad.changeBanner(true, this.adBanner)
    },

    hideBanner() {
        this.adBanner.name = WX_AD_CONFIG.bannerId[0]
        he.ad.changeBanner(false, this.adBanner)
    },

    openNodeConfirm() {
        gg.eventManager.emit('timeCheck')
        this.uiBase.closePage()
    },

    openNodeQuit() {
        this.closeNode.active = false
    },

    //收到点开宝箱的回调
    getTreasure(info) {
        // console.log("打开宝箱了哈")
        // this.isHaveClick.push(info.index)
        switch (info.type) {
            case 1:
                if (this.keyNum > 0) {
                    if (this.keyNum == 0) {
                        this.key_lab.node.color = cc.Color.RED
                    }
                    this.isAni = false
                    this.content.children[info.index].getComponent('gachaItem').clickServer(this.gaChaRes.top, null, this.gaChaList[this.isOpenNum], this.mplist[this.isOpenNum])
                    this.getRes[info.index] = this.isOpenNum
                    this.itemGet()
                    this.isOpenNum += 1
                    this.openNum -= 1
                    this.keyNum -= 1
                    this.treasureNum -= 1
                    this.key_lab.string = `x${this.keyNum}`
                    this.isHaveClick.push(info.index)
                    // this.setKey(this.keyNum)
                } else {
                    gg.uiManager.addTip('没有足够的钥匙')
                }
                break
            case 2:
                this.isHaveClick.push(info.index)
                this.getRes[info.index] = this.isOpenNum
                this.isOpenNum += 1
                this.openNum -= 1
                this.keyNum -= 1
                this.treasureNum -= 1
                // this.setKey(this.keyNum)
                if (this.openNum != 0) {
                    this.oneTimeGet()
                } else {
                    this.isAni = false
                    for (let i = 0; i < this.content.children.length; i++) {
                        this.content.children[i].getComponent(cc.Button).interactable = true
                    }
                }
                break
        }
    },

    //宝箱列表更新
    gachaListInit() {
        let canOpenNum = this.treasureNum
        this.isAni = false
        for (let i = 0; i < this.treasureGrp.length; i++) {
            this.content.children[i].getComponent(cc.Button).interactable = true
        }
        // this.keyNum = this.getKey()
        //取宝箱和钥匙数中少的那个值,能开多少次
        this.openNum = canOpenNum >= this.keyNum ? this.keyNum : canOpenNum
        if (this.keyNum == 0) {
            this.key_lab.node.color = cc.Color.RED
        } else {
            this.key_lab.node.color = cc.Color.WHITE
        }
        this.key_lab.string = `x${this.keyNum}`

    },


    getKey() {
        let bag = he.local.getJson('bag', 'user')
        if (bag && bag.length > 0) {
            let isHave = false
            for (let i = 0; i < bag.length; i++) {
                if (bag[i].id == 30126) {
                    isHave = true
                    return bag[i].num
                }
            }
            if (!isHave) {
                return 0
            }
        } else {
            return 0
        }
    },

    setKey(num) {
        let bag = he.local.getJson('bag', 'user')
        if (bag && bag.length > 0) {
            let isHave = false
            for (let i = 0; i < bag.length; i++) {
                if (bag[i].id == 30126) {
                    isHave = true
                    bag[i].num = num
                    break
                }
            }
            if (!isHave) {
                // bag.push({ id: 30126, num: 3 })
            }
            he.local.setJson('bag', bag, 'user')
        } else {
            // console.log('坏饿了')
        }
    },

    addKey() {
        let bag = he.local.getJson('bag', 'user')
        if (bag && bag.length > 0) {
            let isHave = false
            for (let i = 0; i < bag.length; i++) {
                if (bag[i].id == 30126) {
                    isHave = true
                    bag[i].num += 3
                    break
                }
            }
            if (!isHave) {
                bag.push({ id: 30126, num: 3 })
            }
            he.local.setJson('bag', bag, 'user')
        } else {
            bag = [{ id: 30126, num: 3 }]
            he.local.setJson('bag', bag, 'user')
        }
    },

    creatItem() {
        for (let j = 0; j < 9; j++) {
            let pre = he.pool.getElement('gaChaItem')
            pre.parent = this.content
            // console.log("gaChaRes"+this.gaChaRes+"getRes"+this.getRes)
            pre.getComponent('gachaItem').init(j, this.gaChaRes, this.getRes)
            this.treasureGrp.push(j)
        }

        for (let i = 0; i < this.getRes.length; i++) {
            if (this.getRes[i] != -1) {
                this.isHaveClick.push(i)
            }
            // if(this.)
        }
    },

    useAllKey() {
        if (this.isAni) {
            return
        }

        if (this.treasureNum > 0) {
            let c_num = this.keyNum - this.openNum
            if (c_num == 0) {
                this.key_lab.node.color = cc.Color.RED
            } else if (c_num > 0) {
                this.key_lab.node.color = cc.Color.WHITE
            }
            this.key_lab.string = `x${c_num}`
            this.isAni = true
            this.oneTimeGet()
        }
        else {
            gg.uiManager.addTip('已经开完今日所有宝箱了')
        }
    },


    oneTimeGet() {
        for (let i = 0; i < this.content.children.length; i++) {
            this.content.children[i].getComponent(cc.Button).interactable = false
        }
        let grp = this.getArrDifference(this.treasureGrp, this.isHaveClick)
        if (this.openNum != 0) {
            if (grp && grp.length > 0) {
                this.content.children[grp[0]].getComponent('gachaItem').clickServer(this.gaChaRes.top, 'getAll', this.gaChaList[this.isOpenNum], this.mplist[this.isOpenNum])
                this.itemGet()
            }
        } else {
            this.isAni = false
            gg.uiManager.addTip('没有足够的钥匙或者宝箱')

        }
    },

    itemGet() {
        let itemGrp = this.gaChaList[this.isOpenNum].split('_')
        let info = he.db.getDataByArgs('Item', { id: parseInt(itemGrp[0]) })
        if (info.type == 2 || info.type == 1 || info.type == 4 || info.type == 9) {
            gg.data.addItem(parseInt(itemGrp[0]), parseInt(itemGrp[1]))
        } else {
            let cardBag = he.local.getJson('card', 'user')
            if (cardBag && cardBag.length > 0) {
                cardBag.push({ id: parseInt(info.icon), lv: parseInt(info.rarity) })
            } else {
                cardBag = []
                cardBag.push({ id: parseInt(info.icon), lv: parseInt(info.rarity) })
            }
            he.local.setJson('card', cardBag, 'user')
        }
        gg.eventManager.emit('topBar', UI_Listen.TOP_UPDATE_MONEY)

    },
    getArrDifference(arr1, arr2) {
        return arr1.concat(arr2).filter(function (v, i, arr) {
            return arr.indexOf(v) === arr.lastIndexOf(v);
        });
    },

    watchAd() {
        if (this.isAni) {
            return
        }
        if (this.adNum >= 2) {
            gg.uiManager.addTip('观看次数已达到上限')
            return
        }
        switch (common.sdk_env) {
            case Sdk_Platform.WECHAT:
                util.adFakeTip()
                he.ad.showVideo(() => {
                    this.key_lab.node.color = cc.Color.WHITE
                    this.keyNum += 3
                    this.adNum += 1
                    // this.addKey()
                    this.adAdd()
                    this.gachaListInit()
                })
                break
            case Sdk_Platform.VIVO:
                he.ad.showVideo(() => {
                    he.local.click(`vivo_video_boxPage`)
                    this.key_lab.node.color = cc.Color.WHITE
                    this.keyNum += 3
                    this.adNum += 1
                    // this.addKey()
                    this.adAdd()
                    this.gachaListInit()
                })
                break
            case Sdk_Platform.OPPO:
                he.ad.showVideo(OPPO_AD_CONFIG.videoId[7], () => {
                    this.key_lab.node.color = cc.Color.WHITE
                    this.keyNum += 3
                    this.adNum += 1
                    // this.addKey()
                    this.adAdd()
                    this.gachaListInit()
                })
                break
            case Sdk_Platform.UC:
                he.ad.showVideo(() => {
                    he.local.click(`vivo_video_boxPage`)
                    this.key_lab.node.color = cc.Color.WHITE
                    this.keyNum += 3
                    this.adNum += 1
                    // this.addKey()
                    this.adAdd()
                    this.gachaListInit()
                })
                break
            case Sdk_Platform.HUAWEI:
                he.ad.showVideo(() => {
                    he.local.click(`vivo_video_boxPage`)
                    this.key_lab.node.color = cc.Color.WHITE
                    this.keyNum += 3
                    this.adNum += 1
                    // this.addKey()
                    this.adAdd()
                    this.gachaListInit()
                })
                break
            default:
                this.key_lab.node.color = cc.Color.WHITE
                this.keyNum += 3
                this.adNum += 1
                // this.addKey()
                this.gachaListInit()
                break
        }
    },



    adAdd() {
        let taskGrp = he.local.getJson('task', 'user')
        if (taskGrp && taskGrp.length > 0) {
            for (let j = 0; j < taskGrp.length; j++) {
                if (taskGrp[j].type == 9001) {
                    if (taskGrp[j].num < taskGrp[j].need) {
                        taskGrp[j].num += 1
                    }
                    break
                }
            }
        }
        he.local.setJson('task', taskGrp, 'user')
    },

    scheduleLight() {
        this.lightSD = this.schedule(this.lightServer, 0.05)
    },

    lightServer() {
        this.light.angle += 5
    },

    stopLightSchedule() {
        this.unschedule(this.lightSD)
    },

});
